package com.light.exportproject.controller;

import cn.hutool.extra.template.*;
import com.light.exportproject.utils.GenUtil;
import com.light.exportproject.utils.ZipUtils;
import org.apache.tomcat.util.http.fileupload.FileUtils;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Map;

@RestController
@RequestMapping("/api/project")
public class ProjectController {

    @GetMapping("/generate1")
    public ResponseEntity<Resource> generateProject1(
            @RequestParam String groupId,
            @RequestParam String artifactId,
            @RequestParam String version,
            @RequestParam String applicationName) throws IOException {

        // 参数校验
//        if (!isValidGroupId(groupId) || !isValidArtifactId(artifactId)) {
//            return ResponseEntity.badRequest().build();
//        }
        Map<String, Object> genMap = GenUtil.getGenMap(groupId, artifactId, version, applicationName);

        // 创建临时目录
        Path tempDir = Files.createTempDirectory(artifactId);
        try {
            TemplateEngine engine = TemplateUtil.createEngine(new TemplateConfig("template", TemplateConfig.ResourceMode.CLASSPATH));

            // 创建pom.xml
            Template pomTemplate = engine.getTemplate("generator/pom/Pom.ftl");
            File file = new File(tempDir.toFile(), "pom.xml");
            GenUtil.genFile(file, pomTemplate, genMap);

            // 生成项目结构，并创建MainApplication.java
            generateProjectStructure(tempDir, groupId, artifactId, applicationName, engine, genMap);

            // 压缩为ZIP
            Path zipPath = Files.createTempFile(artifactId + "-", ".zip");
            ZipUtils.zipDirectory(tempDir, zipPath);

            // 构建响应
            Resource resource = new UrlResource(zipPath.toUri());
            return ResponseEntity.ok()
                    .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_OCTET_STREAM_VALUE)
                    .header(HttpHeaders.CONTENT_DISPOSITION,
                            "attachment; filename=\"" + resource.getFilename() + "\"")
                    .body(resource);
        } finally {
            // 清理临时文件（可选）
            FileUtils.deleteDirectory(tempDir.toFile());
        }
    }

    private void generateProjectStructure(Path baseDir, String groupId, String artifactId, String applicationName, TemplateEngine engine, Map<String, Object> genMap) throws IOException {
        // 创建标准Maven目录结构
        Path javaDir = baseDir.resolve("src/main/java/" + groupId.replace(".", "/"));
        Path resourcesDir = baseDir.resolve("src/main/resources");

        Files.createDirectories(javaDir);
        Files.createDirectories(resourcesDir);


        // 注意压缩会忽略空目录，所以必须添加一个文件
        Files.write(resourcesDir.resolve("application.yaml"),
                ("").getBytes());


        // 生成README.md
//        Files.write(baseDir.resolve("README.md"),
//                ("# " + artifactId + "" +"Maven project generated by API" +
//                "Package structure: " + groupId.replace(".", "/")).getBytes());


        Template mainTemplate = engine.getTemplate("generator/default/MainApplication.ftl");
        File file = new File(javaDir.toFile(), applicationName + ".java");
        GenUtil.genFile(file, mainTemplate, genMap);
    }

}

